<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <!--搜索和添加区域-->
          <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!--列表数据-->
      <el-table :data="usersList" border>
        <el-table-column type="index" label="ID"></el-table-column>
        <el-table-column label="姓名" prop="mgName"></el-table-column>
        <el-table-column label="邮箱" prop="mgEmail"></el-table-column>
        <el-table-column label="电话" prop="mgMobile"></el-table-column>
        <el-table-column label="角色" prop="roleName"></el-table-column>
        <el-table-column label="状态">
          <!--通过作用域-->
          <template v-slot="scope">
            <el-switch @change="userStateChange(scope.row)"
                       v-model="scope.row.mgState"
                       :active-value="1"
                       :inactive-value="0"
                       active-text="开启"
                       inactive-text="关闭">

            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <!--编辑按钮-->
            <el-tooltip class="dark" effect="dark" content="编辑用户" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" @click="showDialogVisible(scope.row.mgId)"></el-button>
            </el-tooltip>
            <!--删除按钮-->
            <el-tooltip class="dark" effect="dark" content="删除用户" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" @click="removeUser(scope.row.mgId)"></el-button>
            </el-tooltip>
            <!--角色按钮-->
            <el-tooltip class="dark" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-star-off" @click="showAddRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageIndex"
        :page-sizes="[1, 2, 4, 5]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!--添加用户弹框-->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%" @close="closeAddDialog">
      <el-form  :model="addForm"
               label-width="70px"
               :rules="addFormRules" ref="addFormRef">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="addForm.pwd"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
    </el-dialog>

    <!--编辑用户弹框-->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="50%" @close="editDialogClose">
      <el-form label-width="70px" :model="editForm" :rules="editFormRules" ref="editFormRef">
        <el-form-item label="用户名">
          <el-input v-model="editForm.mgName" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="mgEmail">
          <el-input v-model="editForm.mgEmail"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mgMobile">
          <el-input v-model="editForm.mgMobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!--分配角色对话框-->
    <el-dialog
      title="分配角色"
      :visible.sync="addRoleDialogVisible"
      width="50%" @close="closeAddUserDialog">
      <div>
        <p>用户名称: {{userInfo.mgName}}</p>
        <p>用户角色: {{userInfo.roleName}}</p>
        <p>分配新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUserRole">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
    export default {
        name: "Users",
      data(){
          //自定义检验规则
          let checkEmail = (rule,value,cb) =>{
            let regEmail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            if(regEmail.test(value)){
              return cb();
            }
            cb(new Error('请输入合法邮箱'));
          };
          let checkMobile = (rule,value,cb) =>{
            let regMobile = /^1[3|4|5|7|8][0-9]{9}$/;
            if(regMobile.test(value)) {
              return cb();
            } else{
              cb(new Error('请输入合法手机号'))
            }
            if(value <11) {
              cb(new Error('手机号为11位'))
            }else {
              return cb();
            }
          };
          //定义页面属性
          return {
            queryInfo: {
              query: '',
              pageIndex: 1,
              pageSize: 2
            },
            usersList:[],
            total:0,
            //控制添加用户弹框显示和隐藏属性
            addDialogVisible:false,
            //编辑用户弹框显示和隐藏
            editDialogVisible:false,
            editForm:{},
            //添加用户表单属性
            addForm:{
              name:'',
              pwd:'',
              email:'',
              mobile:''
            },
            //添加用户表单校验规则
            addFormRules:{
              name:[
                {required:true,message: '请输入用户名',trigger:'blur'},
                {min:3,max: 10,trigger:'blur',message:'用户名长度在3~10个字符'}
              ],
              pwd:[
                {required: true,message:'请输入密码',trigger:'blur'},
                {min: 6,max:10,message:'密码长度在6~10个字符',trigger:'blur'}
              ],
              email:[
                {required: true,message:'请输入邮箱',trigger:'blur'},
                {validator: checkEmail,trigger:'blur'}
              ],
              mobile:[
                {required: true,message:'请输入手机号',trigger:'blur'},
                {validator: checkMobile,trigger:'blur'}
              ]
            },
            //编辑用户表单校验规则
            editFormRules:{
              mgEmail:[
                  {required: true,message:'请输入邮箱',trigger:'blur'},
                  {validator: checkEmail,trigger:'blur'}
                ],
              mgMobile:[
                {required: true,message:'请输入手机号',trigger:'blur'},
                {validator: checkMobile,trigger:'blur'}
              ]
            },
            //分配角色对话框显示和隐藏
            addRoleDialogVisible:false,
            //分配角色保存信息
            userInfo:{},
            //角色列表数据
            roleList:[],
            //角色列表选中的值
            selectedRoleId:''
          }
      },
      created() {
        this.getUserList();
      },
      methods:{
        async getUserList(){
          const {data:res} = await this.$axios.get("managerList",{params:this.queryInfo});
          //console.log(res)
          if(res.code == 200) {
            this.usersList = res.data.users;
            this.total = res.data.total;
            //console.log(this.usersList+"==="+this.total);
          }
        },
        //监听pageSize改变事件
        handleSizeChange(val){
          this.queryInfo.pageSize = val;
          //渲染页数重新触发列表数据
          this.getUserList();
        },
        //监听当前页改变事件
        handleCurrentChange(val){
          this.queryInfo.pageIndex = val;
          this.getUserList();
        },
        //监听switch改变事件
        async userStateChange(val){
          //console.log(val.mgId);
          const {data:res} = await this.$axios.put('user/'+val.mgId+'/state/'+val.mgState);
          if(res.code == 200) {
             this.$message({
               message:"恭喜您，修改成功",
               type:"success"
             });
          }
        },
        //重置弹框里面默认属性值事件
        closeAddDialog(){
          this.$refs.addFormRef.resetFields();
        },
        //点击添加用户事件
        addUser(){
          this.$refs.addFormRef.validate(async valid=>{
            if(!valid) return;
            //this.$message.success("检验成功");
            const {data:res} = await this.$axios.post("addUser",this.addForm);
            if(res.code != 200)this.$message.error("添加用户失败");
            this.$message.success("添加用户成功");
            //隐藏弹框
            this.addDialogVisible = false;
            this.getUserList();
          });
        },
        //点击编辑按钮显示弹框
        async showDialogVisible(val) {
          const {data:res} = await this.$axios.get("user/"+val);
          //console.log(res.data);
          if(res.code != 200) {
            return this.$message.error("查询用户不存在");
          }
          this.editForm = res.data;
          //显示弹框
          this.editDialogVisible = true;
        },
        //编辑弹框重置验证表单事件
        editDialogClose(){
          this.editForm = {};
          this.$refs.editFormRef.resetFields();
        },
        //修改用户信息并提交事件
        editUser(){
          this.$refs.editFormRef.validate(async valid=>{
            if(!valid) return;
            const {data:res} = await this.$axios.put("user/"+this.editForm.mgId,
              'mgEmail='+this.editForm.mgEmail+'&mgMobile='+this.editForm.mgMobile);
            //console.log(this.editForm.mgEmail);
            if(res.code !=200) {
              return this.$message.error("修改失败");
            }
            //修改成功后隐藏弹框
            this.editDialogVisible = false;
            this.getUserList();
            this.$message.success("修改成功");
          })
        },
        //删除用户点击事件
        async removeUser(val){
          const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err=>err);
          //console.log(confirmResult);
          if(confirmResult != 'confirm') {
            return this.$message.info("已取消删除");
          }
          const {data:res} = await this.$axios.delete("delete/"+val);
          if(res.code !=200) {
            return this.$message.error("删除失败")
          }
          this.$message.success("删除成功");
          this.getUserList();
        },
        //分配角色对话框弹窗
        async showAddRoleDialog(row){
          this.userInfo = row;
          this.addRoleDialogVisible = true;

          const {data:res} = await this.$axios.get("roles");
          if(res.code != 200) {
            return this.$message.error("获取角色列表失败")
          }
          this.roleList = res.data;
          console.log(res);
          this.$message.success("获取角色列表成功")
        },
        //添加用户角色按钮
        async addUserRole(){
          if(!this.selectedRoleId) {
             return this.$message.info("请选中重新分配的角色")
          }
          const {data:res} = await this.$axios.put("/update/"+this.userInfo.mgId+"/role",
            "roleId="+this.selectedRoleId);
          if(res.code != 200) {
              return this.$message.error("分配角色失败")
          }
          this.$message.success("分配角色成功");
          this.getUserList();
          this.addRoleDialogVisible = false;
        },
        //关闭分配权限对话框
        closeAddUserDialog(){
            this.userInfo = {};
            this.selectedRoleId = '';
        }
      }
    }
</script>

<style scoped>
  .el-breadcrumb{
    margin-bottom: 15px;
  }
  .el-card{
    box-shadow: 0 1px 1px rgba(0,0,0,0.15) !important;
  }
  .el-table{
    margin-top: 15px;
  }
  .el-pagination{
    margin-top: 15px;
  }
</style>
